#!/usr/bin/env bash

set -e

VERSION=${1:-2016.09.16}
echo "Generate and install RPM for autoconf-archive-$VERSION"

WORK_DIR=/tmp/autoconf-archive-rpmbuilder
mkdir -p $WORK_DIR

SPEC_FILE=$WORK_DIR/autoconf-archive.spec
echo "Generate spec file at $SPEC_FILE"
cat autoconf-archive.spec.template | sed s/__VERSION__/$VERSION/g > $SPEC_FILE

echo "Ensure all dependencies are available..."
yum install -y rpm-build rpmdevtools yum-utils make

echo "Build RPM from source..."
SRPM_FILE=/usr/src/redhat/SRPMS/autoconf-archive-$VERSION-1.src.rpm
pushd $WORK_DIR
spectool -g -R autoconf-archive.spec
rpmbuild -bs autoconf-archive.spec
yum-builddep $SRPM_FILE
rpmbuild --rebuild $SRPM_FILE
popd

RPM_FILE=/usr/src/redhat/RPMS/noarch/autoconf-archive-$VERSION-1.noarch.rpm
echo "Install RPM from $RPM_FILE"
rpm -i $RPM_FILE

echo "Clean up $WORK_DIR"
rm -rf $WORK_DIR
rm -f $SRPM_FILE
rm -f $RPM_FILE
